(function($) {
	jQuery.WebSocketMgr = function() {
		var serverUrl = 'ws://192.168.1.200:9090/chat';
		var wsConnection = {};
		wsConnection.logined = false;
		var callBack;
		/*初始化websocket*/
		function initConnection(cb) {
			callBack=cb;
			if(!!wsConnection.websocket) {
				wsConnection.websocket.close();
			}

			wsConnection.websocket = new WebSocket(serverUrl);
			wsConnection.websocket.binaryType = "arraybuffer";
			//var imConnection = new WebSocket(imConnectionUrl);
			wsConnection.websocket.onopen = wsOpen;
			wsConnection.websocket.onmessage = wsMessage;
			wsConnection.websocket.onclose = wsClose;
		}
		var connection = wsConnection;
		/*连接服务端*/
		function wsOpen(event) {
			console.log('connect to im success');
			wsConnection.clientState = UserStatType.USER_STATUS_ONLINE;
			if(wsConnection.logined && !!wsConnection.loginInfo) {
				relogin(function(res, error) {
					if(res) {
						console.log('relogin success');
					}
				});
			}

		}
		/*关闭连接*/
		function wsClose(event) {
			if(!window.navigator.onLine) {
				wsConnection.clientState = UserStatType.USER_STATUS_OFFLINE;
			} else if(wsConnection.logined) {
				initConnection();
			}
		}
		/*收到数据*/
		function wsMessage(event) {
			var pdu = event.data.slice(0, 16);
			var ByteBuffer = dcodeIO.ByteBuffer;
			var pduBB = new ByteBuffer();
			pduBB.append(pdu);
			console.log("serviceId:" + pduBB.readUInt16(8) + "  commandId:" + pduBB.readUInt16(10) + "  seqNum:" + pduBB.readUInt16(12));
			var data = {};
			data.commandId = pduBB.readUInt16(10);
			data.seqNum = pduBB.readUInt16(12);
			data.serviceId = pduBB.readUInt16(8);
			data.content = event.data;
			//handleEventData(data);
			if(callBack)callBack(data.commandId, data);
			else console.log("消息未设置处理方法！");
		}
		/*发送消息*/
		function sendMsg(argument) {
			wsConnection.websocket.send(Base64.encode(argument));
		}
		/*发送2进制数据*/
		function sendBinaryData(binaryData) {
			wsConnection.websocket.send(binaryData);
		}
		return {
			serverUrl:serverUrl,
			wsConnection:wsConnection,
			initConnection:initConnection,
			connection:connection,
			callBack:callBack,
			wsOpen:wsOpen,
			wsClose:wsClose,
			wsMessage:wsMessage,
			sendMsg:sendMsg,
			sendBinaryData:sendBinaryData
		};
	}
})($);